<?php
namespace app\admin\model;


use Exception;

class AdminRole extends Base
{

    /**
     * @param AdminRole $model
     * @return void
     * @throws Exception
     */
    public static function onAfterInsert(AdminRole $model): void
    {
        // 添加角色权限
        self::addMenu($model);
    }


    /**
     * @param AdminRole $model
     * @return void
     * @throws Exception
     */
    public static function onBeforeUpdate(AdminRole $model): void
    {
        // 添加角色权限
        self::addMenu($model);
    }


    /**
     * @param AdminRole $model
     * @return void
     * @throws Exception
     */
    public static function onBeforeDelete(AdminRole $model): void
    {
        if($ids = $model->adminRoleMenus()->column('id'))AdminRoleMenu::destroy($ids,true);
    }


    /**
     * @param $model
     * @return void
     * @throws Exception
     */
    public static function addMenu($model): void
    {
        if($menu_ids = request()->param('menu_ids',0)){
            $arr = explode(',',$menu_ids);
            $data = [];
            foreach ($arr as $v){
                $array['admin_role_id'] = $model->id;
                $array['admin_menu_id'] = $v;
                $data[] = $array;
            }
            if($ids = $model->adminRoleMenus()->column('id'))AdminRoleMenu::destroy($ids,true);
            (new AdminRoleMenu())->saveAll($data);
        }
    }
}